<template>
  <view class="list-page">
    <!-- 头部 -->
    <view class="list-header">
      <view class="header-back" @click="goBack">
        <text class="iconfont icon-zuojiantou-copy"></text>
      </view>
      <view class="header-title">
        <text class="title-text">{{ listData.name || '歌单' }}</text>
      </view>
    </view>

    <!-- 封面和描述 -->
    <view class="list-cover">
      <image 
        :src="listData.coverImgUrl || '/static/placeholder.png'" 
        class="cover-img" 
        mode="aspectFill" 
      />
      <text class="cover-description">{{ listData.description || '暂无描述' }}</text>
    </view>

    <!-- 播放全部按钮 -->
    <view class="play-all-container">
      <button class="play-all-btn" @click="playAll">
        <text class="iconfont icon-bofang play-all-icon"></text>
        <text class="play-all-text">播放全部 (共{{ displayTrackCount }}首)</text>
      </button>
    </view>

    <!-- 歌曲列表 -->
    <scroll-view class="list-container" scroll-y :style="{ height: scrollHeight + 'px' }">
      <view 
        class="list-item" 
        v-for="(item, index) in songList" 
        :key="item.id"
        @click="playSong(item, index)"
      >
        <text class="item-rank" :class="{ 'top-rank': index < 3 }">{{ index + 1 }}</text>
        <view class="item-info">
          <text v-if="item.fee === 1" class="vip-tag">VIP</text>
          <text class="sq-tag" v-if="item.sq">SQ</text>
          <text class="item-name">{{ item.name }}</text>
          <text class="item-artist">{{ item.ar.map(artist => artist.name).join('/') }}</text>
        </view>
        <view class="item-actions">
          <text class="iconfont icon-bofang1"></text>
        </view>
      </view>

      <!-- 加载状态 -->
      <view class="loading-status" v-if="loading">
        <text>加载中...</text>
      </view>
      <view class="loading-status" v-else-if="songList.length === 0">
        <text>暂无歌曲</text>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { listDetail } from '@/common/api.js';

export default {
  data() {
    return {
      listData: {}, // 歌单基本信息
      songList: [], // 歌曲列表
      loading: false,
      id: null, // 歌单ID
      scrollHeight: 0 // 滚动区域高度
    };
  },
  computed: {
    displayTrackCount() {
      return Math.min(this.listData.trackCount || 0, 100);
    }
  },
  onLoad(options) {
    if (options.id) {
      this.id = options.id;
      this.calculateScrollHeight();
      this.fetchPlaylistDetail();
    } else {
      uni.showToast({
        title: '缺少歌单ID',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  },
  onReady() {
    // 页面初次渲染完成后再次计算高度
    this.calculateScrollHeight();
  },
  onResize() {
    // 屏幕尺寸变化时重新计算高度
    this.calculateScrollHeight();
  },
  methods: {
    calculateScrollHeight() {
      const query = uni.createSelectorQuery().in(this);
      query.select('.list-container').boundingClientRect(rect => {
        if (rect) {
          this.scrollHeight = rect.height;
        } else {
          // 默认高度，确保在无法获取准确高度时也能正常显示
          this.scrollHeight = 500;
        }
      }).exec();
    },

    // 获取歌单详情
    async fetchPlaylistDetail() {
      this.loading = true;
      try {
        const res = await listDetail(this.id);
        console.log('歌单详情:', res);

        // 检查接口返回格式
        if (!Array.isArray(res) || res.length < 2 ||!res[1]?.data?.playlist) {
          throw new Error('接口返回数据格式错误');
        }

        const playlist = res[1].data.playlist;
        this.listData = {
          id: playlist.id,
          name: playlist.name,
          coverImgUrl: playlist.coverImgUrl,
          description: playlist.description,
          trackCount: playlist.trackCount,
          playCount: playlist.playCount,
          creator: playlist.creator
        };

        // 处理歌曲列表，统一限制为100首
        this.songList = playlist.tracks.slice(0, 100).map(track => ({
          id: track.id,
          name: track.name,
          ar: track.ar,
          al: track.al,
          dt: track.dt, // 歌曲时长
          fee: track.fee, // 1表示VIP歌曲
          sq: track.sq, // 是否有SQ品质
          url: '' // 后续获取播放地址
        }));

        console.log('成功加载', this.songList.length, '首歌曲');

      } catch (error) {
        console.error('获取歌单详情失败:', error);
        uni.showToast({
          title: '获取歌单详情失败',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },

    // 返回上一页
    goBack() {
      uni.navigateBack();
    },

    // 播放全部
    playAll() {
      if (this.songList.length === 0) {
        uni.showToast({
          title: '当前歌单暂无歌曲',
          icon: 'none'
        });
        return;
      }

      uni.showToast({
        title: `开始播放 ${this.songList.length} 首歌曲`,
        icon: 'none'
      });

      // 实际项目中可以调用播放器API
      // this.$store.dispatch('player/setPlaylist', this.songList);
      // this.$store.dispatch('player/play', 0);
    },

    // 播放单曲
    playSong(song, index) {
      if (song.fee === 1) {
        uni.showToast({
          title: 'VIP歌曲，开通会员后播放',
          icon: 'none'
        });
        return;
      }

      uni.showToast({
        title: `播放: ${song.name}`,
        icon: 'none'
      });

       // 跳转到播放页面并传递歌曲信息
        uni.navigateTo({
            url: `/pages/play/play?id=${song.id}&name=${encodeURIComponent(song.name)}&artists=${encodeURIComponent(song.ar.map(artist => artist.name).join('/'))}&coverImgUrl=${encodeURIComponent(song.al.picUrl)}`
        });
    }
  }
};
</script>

<style lang="scss">
.list-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #FFF0F0;
}

.list-header {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;

  .header-back {
    margin-right: 20rpx;

    .iconfont {
      font-size: 36rpx;
      color: #333;
    }
  }

  .header-title {
    flex: 1;

    .title-text {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      display: block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}

.list-cover {
  position: relative;
  padding: 30rpx;
  background: #fff;

  .cover-img {
    width: 100%;
    height: 300rpx;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  }

  .cover-description {
    font-size: 24rpx;
    line-height: 1.5;
    color: #666;
    display: block;
    padding: 0;
  }
}

.play-all-container {
  padding: 20rpx 30rpx;
  background-color: #fff;
  display: flex;
  justify-content: flex-start;
  width: 100%;
  box-sizing: border-box;
}

.play-all-btn {
  background-color: #d43c33;
  color: #fff;
  border: none;
  border-radius: 40rpx;
  font-size: 28rpx;
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0;

  .play-all-icon {
    font-size: 36rpx;
    margin-right: 10rpx;
    color: #fff;
  }
}

.list-container {
  flex: 1;
  background-color: #fff;
  padding: 0 30rpx;
}

.list-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;

  .item-rank {
    width: 60rpx;
    text-align: center;
    font-size: 28rpx;
    color: #999;

    &.top-rank {
      color: #d43c33;
      font-weight: bold;
    }
  }

  .item-info {
    flex: 1;
    overflow: hidden;

    .vip-tag {
      background-color: #f90;
      color: white;
      font-size: 20rpx;
      padding: 2rpx 6rpx;
      border-radius: 4rpx;
      margin-right: 8rpx;
    }

    .sq-tag {
      background-color: #d43c33;
      color: white;
      font-size: 20rpx;
      padding: 2rpx 6rpx;
      border-radius: 4rpx;
      margin-right: 8rpx;
    }

    .item-name {
      font-size: 28rpx;
      color: #333;
      display: block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      line-height: 1.5;
    }

    .item-artist {
      font-size: 24rpx;
      color: #999;
      display: block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .item-actions {
    padding-left: 20rpx;

    .iconfont {
      font-size: 36rpx;
      color: #999;
    }
  }
}

.loading-status {
  padding: 40rpx 0;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}
</style>